package com.qifei.xmlg_backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qifei.xmlg_backend.DTO.student.StudentQueryParam;
import com.qifei.xmlg_backend.entity.Result;
import com.qifei.xmlg_backend.entity.Student;
import com.qifei.xmlg_backend.service.IStudentService;
import io.jsonwebtoken.io.IOException;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 学生表 前端控制器
 * </p>
 *
 * @author qifei
 * @since 2025-06-11
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private IStudentService studentService;

    @GetMapping("")
    public Result<?> getAll(@ModelAttribute  StudentQueryParam param ){
        QueryWrapper<Student> query = new QueryWrapper<>();

        if (StringUtils.hasText(param.getName())) query.like("name", param.getName());
        if (param.getGender() != null) query.eq("gender", param.getGender());
        if (param.getBirthDate() != null) query.eq("birth_date", param.getBirthDate());
        if (param.getClassId() != null) query.eq("class_id", param.getClassId());
        if (param.getStatus() != null) query.eq("status", param.getStatus());

        Page<Student> page = new Page<>(param.getPageNum(), param.getPageSize());
        Page<Student> resultPage = studentService.page(page, query);

        return Result.success(resultPage);
    }

    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable int id){
        Student stu = studentService.getById(id);
        return Result.success(stu);
    }

    @PostMapping()
    public Result<?> add(@RequestBody Student student){
        boolean success = studentService.save(student);
        if (!success) {
            return Result.error("添加学生失败");
        }

        return Result.success();
    }

    @PutMapping()
    public Result<?> put(@RequestBody Student student){
        boolean success = studentService.updateById(student);
        if (!success) {
            return Result.error("更新学生失败");
        }

        return Result.success();
    }


    @DeleteMapping("/{ids}")
    public Result<?> delete(@PathVariable String ids) {
        String[] idArray = ids.split(",");
        if (idArray.length == 1) {
            // 单个删除
            boolean removed = studentService.removeById(Long.valueOf(idArray[0]));
            return removed ? Result.success("删除成功") : Result.error("删除失败");
        }
        List<Long> idList = Arrays.stream(ids.split(",")).map(Long::valueOf).toList();
        boolean removed = studentService.removeByIds(idList);
        if (removed) {
            return Result.success("批量删除成功");
        } else {
            return Result.error("批量删除失败");
        }

    }

    /**
     * 学生导入
     * */
    @PostMapping("/import")
    public Result<?> importExcel(@RequestParam("file") MultipartFile file) {
        studentService.importExcel(file);
        return Result.success("导入成功");
    }

    /**
     * 学生导出
     * */
    @PostMapping("/export")
    public void exportSelected(@RequestBody List<Integer> ids, HttpServletResponse response) throws IOException {
        studentService.exportSelected(ids, response);
    }

    /**
     * 获取学生性别统计数据
     */
    @GetMapping("/gender/stats")
    @ApiOperation(value = "获取学生性别统计数据")
    public Result<?> getStudentGenderStats() {
        return Result.success(studentService.getStudentGenderStats());
    }

    /**
     * 获取学生状态统计数据
     */
    @GetMapping("/status/stats")
    @ApiOperation(value = "获取学生状态统计数据")
    public Result<?> getStudentStatusStats() {
        return Result.success(studentService.getStudentStatusStats());
    }

    /**
     * 获取学生加入时间统计数据（按月份）
     */
    @GetMapping("/joindate/stats")
    @ApiOperation(value = "获取学生加入时间统计数据（按月份）")
    public Result<?> getStudentJoinDateStats() {
        return Result.success(studentService.getStudentJoinDateStats());
    }


}
